import sys
from PySide6.QtWidgets import QWidget, QGridLayout, QLabel, QPushButton, QLineEdit, QMessageBox, QComboBox, QApplication, QTextEdit
from easy_tools.utils.cryptography import *


class CodecWidget(QWidget):
    def __init__(self):
        super().__init__()
        self._init()

    def _init(self):
        grid = QGridLayout(self)
        self.setLayout(grid)
        self.code_types = QComboBox(self)
        self.code_types.addItem('MD5', 'md5')
        self.code_types.addItem('Base64', 'base64')
        self.code_types.addItem('HMAC_SHA256', 'hmac_sha256')
        self.code_modes = QComboBox(self)
        self._update_code_modes()
        self.char_modes = QComboBox(self)
        self.char_modes.addItem('默认', 'default')
        self.char_modes.addItem('大写', 'upper')
        self.char_modes.addItem('小写', 'lower')
        self.input_text_widget = QTextEdit('', self)
        self.output_text_widget = QTextEdit('', self)
        self.confirm = QPushButton('转换', self)
        self.extend_widget = QWidget(self)
        self.extend_meta = {}

        x = 0
        grid.addWidget(QLabel('编码类型: ', self), x, 0, 1, 1)
        grid.addWidget(self.code_types, x, 1, 1, 1)
        grid.addWidget(self.code_modes, x, 2, 1, 1)
        grid.addWidget(self.char_modes, x, 3, 1, 1)
        x += 1
        # 拓展组件高度
        self.extend_height = x
        # grid.addWidget(QLabel('原始串: ', self), x, 0, 1, 2)
        # grid.addWidget(self.input_text_widget, x, 2, 1, 2)
        x += 1
        # grid.addWidget(QLabel('结果: ', self), x, 0, 1, 2)
        # grid.addWidget(self.output_text_widget, x, 2, 1, 2)
        x += 1
        grid.addWidget(self.confirm, x, 0, 1, 4)
        self._init_common_extend()
        self.code_types.currentIndexChanged.connect(self._code_type_changed)
        self.confirm.clicked.connect(self._handle)

    def _init_common_extend(self):
        """ 初始化通用拓展 """
        self._close_extend()
        self.extend_widget = QWidget(self)
        grid = QGridLayout(self.extend_widget)
        x = 0
        grid.addWidget(QLabel('原始串: ', self), x, 0, 1, 1)
        grid.addWidget(self.input_text_widget, x, 2, 1, 3)
        x += 1
        grid.addWidget(QLabel('结果: ', self), x, 0, 1, 1)
        grid.addWidget(self.output_text_widget, x, 2, 1, 3)
        self.layout().addWidget(self.extend_widget, self.extend_height, 0, 1, 4)

    def _init_hmac_extend(self):
        """ 初始化HMAC编码拓展组件 """
        self._close_extend()
        self.extend_widget = QWidget(self)
        grid = QGridLayout(self.extend_widget)
        x = 0
        self.extend_meta['hmac_key'] = QTextEdit('', self)
        grid.addWidget(QLabel('Key: ', self), x, 0, 1, 1)
        grid.addWidget(self.extend_meta['hmac_key'], x, 1, 1, 1)
        grid.addWidget(QLabel('内容: ', self), x, 2, 1, 1)
        grid.addWidget(self.input_text_widget, x, 3, 1, 1)
        x += 1
        grid.addWidget(QLabel('结果: ', self), x, 0, 1, 1)
        grid.addWidget(self.output_text_widget, x, 1, 1, 3)
        self.layout().addWidget(self.extend_widget, self.extend_height, 0, 1, 4)

    def _update_code_modes(self, encode=True, decode=False):
        self.code_modes.clear()
        if encode:
            self.code_modes.addItem('编码', 'encode')
        if decode:
            self.code_modes.addItem('解码', 'decode')

    def _code_type_changed(self):
        v = self.code_types.currentData()
        if v in ('base64', ):
            self._update_code_modes(encode=True, decode=True)
            return
        if v == 'hmac_sha256':
            self._init_hmac_extend()
        self._update_code_modes(encode=True, decode=False)

    def _handle(self):
        value = self.code_types.currentData()
        try:
            output = ''
            if value == 'md5':
                output = md5(self.input_text_widget.toPlainText().strip())
            elif value == 'md5_16':
                output = md5(self.input_text_widget.toPlainText().strip(), digit=Md5DigitEnum.MD5_16)
            elif value == 'md5_64':
                output = md5(self.input_text_widget.toPlainText().strip(), digit=Md5DigitEnum.MD5_64)
            elif value == 'base64':
                if self.code_modes.currentData() == 'encode':
                    output = encode_base64(self.input_text_widget.toPlainText().strip()).decode('utf-8')
                else:
                    output = decode_base64(self.input_text_widget.toPlainText().strip()).decode('utf-8')
            if not output:
                raise Exception('解析失败')
            if self.char_modes.currentData() == 'upper':
                output = output.upper()
            elif self.char_modes.currentData() == 'lower':
                output = output.lower()
            self.output_text_widget.setText(output)
        except Exception as e:
            QMessageBox.question(self, '错误', '转换失败, 请检查输入串是否合法', QMessageBox.StandardButton.Ok)

    def _close_extend(self):
        if self.extend_widget:
            self.layout().removeWidget(self.extend_widget)
            self.extend_widget.close()


if __name__ == '__main__':
    app = QApplication()
    win = CodecWidget()
    win.show()
    sys.exit(app.exec())
